from sqlalchemy import Column, String, DateTime, ForeignKey, JSON, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.database.base import Base
import uuid

class Device(Base):
    __tablename__ = "devices"
    
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name = Column(String(255), nullable=False, index=True)
    device_type = Column(String(100), nullable=False, index=True)
    model = Column(String(100))
    manufacturer = Column(String(100))
    serial_number = Column(String(100), unique=True, index=True)
    location = Column(String(255), index=True)
    specifications = Column(JSON)
    status = Column(String(20), default="active", nullable=False, index=True)
    description = Column(Text)
    owner_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    last_maintenance = Column(DateTime(timezone=True))
    
    owner = relationship("User", back_populates="devices")
    maintenance_records = relationship("MaintenanceRecord", back_populates="device", cascade="all, delete-orphan")
    maintenance_plans = relationship("MaintenancePlan", back_populates="device", cascade="all, delete-orphan")